package ua.pp.parkee.t1;

import java.util.concurrent.Callable;

public class SinCosSum implements Callable<Double> {

    private double step;
    private double start;
    private double end;
    private int threadNum;
    private int threads;
    private int roundTo;
    private final Function function;


    public SinCosSum(double start, double end, double step, int threadNum, int threads, Function function) {
        this.start = start;
        this.end = end;
        this.step = step;
        this.threadNum = threadNum;
        this.threads = threads;
        this.function = function;
        this.roundTo = getPrecision(step);
    }

    @Override
    public Double call() {
        double offset = roundTo(step * threads, roundTo);
        double sum = 0.0;
        for (double i = start + threadNum * step; i <= end ; i = roundTo(i + offset, roundTo)) {
            sum += function.calc(i);
        }
        return sum;
    }

    int getPrecision(double n) {

        return (int)(1 / n);
    }

    private double roundTo(double n, double to) {
        return Math.round(n * to) / to;
    }

}